import React from 'react';
import {Link} from 'react-router-dom'
import {Input, Button, Row, Col, Form, Select, Divider, Popconfirm, message} from 'antd';
import Grid from '../../components/table/grid';
import ModifyCarForm from './modifyCarForm';
import axios from 'axios';
import {injectIntl} from 'react-intl';
import BindVIN from './bindVIN';
import RemoveVIN from './removeVIN';
import DepartmentPicker from '../../components/pickCity/departmentPicker';
import AuthButton from '../../components/auth/authButton';
import {sessionManager} from '../../utils/sessionStorage';


const Option = Select.Option;
const FormItem = Form.Item;
const createForm = Form.create;

class carManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedRowKeys: [],
            selectedStations: [],
            visible: false,
            visible4VIN: false,
            visible4removeVIN: false,
            params: {
                plateNo: ``
            },
            selectedInfo: {},
            selectedCarID: '',
            selectedCarVIN: '',
            refresh: 0
        };
        const common = this.props.intl.messages.common;
        this.columns = [
            {
                title: common.ownCode,
                dataIndex: 'num',
                key: 'num',
            },
            {
                title: common.licenseNumber,
                dataIndex: 'plateNo',
                key: 'plateNo',
            },
            {
                title: common.VIN,
                dataIndex: 'vin',
                key: 'vin',
            },
            {
                title: common.belongDep,
                dataIndex: 'levelOne',
                key: 'levelOne',
            },
            {
                title: common.belongDep,
                dataIndex: 'levelTwo',
                key: 'levelTwo',
            },
            {
                title: common.belongDep,
                dataIndex: 'levelThree',
                key: 'levelThree',
            },
            {
                title: common.operation,
                width: '20%',
                key: 'action',
                render: (text, record) => (
                    <span>
                        <span data-auth="007003005">
                        <a onClick={() => this.modifyCar(text, record)}>{common.modify}</a>
                        <Divider type="vertical"/>
                        </span>
                        {/*<a onClick={()=>this.openRemoveModal(text,record)}>{common.stub}</a>*/}
                        {/*<Divider type="vertical" />*/}
                        <Popconfirm title={`${common.VerifyPerformed}?`} okText={common.sure}
                                    onConfirm={() => this.deleteStaff(text, record)} cancelText={common.cancel}>
                            <a data-auth="007003004">{common.delete}</a>
                        </Popconfirm>
                    </span>
                )
            }
        ];
    }

    //
    downLoad = (text) => {
        axios.post('/api/user/car/export', {
            ...{
                plateNo: text.plateNo,
                vin: text.vin
            }
        }).then(res => {
        })
    }

    //删除数据
    deleteStaff = (text) => {
        axios.post('/api/user/car/del', {...{id: text.id}}).then(res => {
            if (res && res.code == 200) {
                this.setState({
                    visible: false,
                    refresh: this.state.refresh + 1
                });
            }
        })
    }
    //修改数据
    saveFormRef = (formRef) => {
        this.formRef = formRef;
    }
    //打开弹框
    openRemoveModal = (text) => {
        this.setState({
            visible4removeVIN: true,
            selectedCarVIN: text.vin,
        });
    }

    modifyCar = (text) => {
        console.log(text);

        this.setState({
            visible: true,
            selectedCarID: text.id,
            selectedInfo: text
        });

    }
    //取消关闭弹框
    handleCancel = () => {
        const form = this.formRef.props.form;
        form.resetFields();
        this.setState({
            visible: false,
            visible4VIN: false,
            visible4removeVIN: false
        });
    }
    //提交表单
    handleCreate = () => {
        const form = this.formRef.props.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            values.id = this.state.selectedCarID;
            axios.post('/api/user/car/model', {...values}).then(res => {
                if (res) {
                    this.setState({
                        visible: false,
                        refresh: this.state.refresh + 1
                    });
                    form.resetFields();
                }
            })
        });
    };
    openVINModal = () => {
        if (this.state.selectedRowKeys.length === 0) {
            message.warn('请选择车辆');
            return
        }
        this.setState({
            visible4VIN: true
        })
    };

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            this.setState({
                params: {...values},
                refresh: this.state.refresh + 1
            });
        });
    }

    render() {
        const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
        // const token = JSON.parse(sessionStorage.getItem("token")).token;
        const {getFieldDecorator} = this.props.form;
        const marginRight8 = {
            marginRight: 8
        };
        let locale=sessionManager.get('locale');
        const common = this.props.intl.messages.common;
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRow) => {
                this.setState({
                    selectedRowKeys: selectedRow
                }, () => {
                    console.log(this.state)
                })
            },
        };
        return (
            <AuthButton>
                <div>
                    <ModifyCarForm
                        selectedInfo={this.state.selectedInfo}
                        wrappedComponentRef={this.saveFormRef}
                        visible={this.state.visible}
                        onCancel={this.handleCancel}
                        onCreate={this.handleCreate}
                    />
                    <form form={this.props.form}>
                        <Row gutter={16}>
                            <Col span={3}>
                                <FormItem
                                >
                                    {getFieldDecorator('plateNo')(
                                        <Input placeholder={common.licenseNumber}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={3}>
                                <FormItem
                                >
                                    {getFieldDecorator('org')(
                                        <DepartmentPicker placeholder={common.department}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={3}>
                                <FormItem
                                >
                                    {getFieldDecorator('num')(
                                        <Input placeholder={common.ownCode}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem>
                                    <Button className="ant-btn-84" type="primary" onClick={this.handleSubmit}
                                            style={marginRight8}>{common.search}</Button>
                                    <Link to="/staff/addCar">
                                        <Button type="primary" className="ant-btn-84" data-auth={'007003002'}
                                                style={marginRight8}>{common.addCar}</Button>
                                    </Link>
                                    <a href={`${axios.defaults.baseURL}/api/user/car/export?plateNo=${this.state.params.plateNo ? this.state.params.plateNo : ''}&token=${token}&locale=${locale}`}>
                                        <Button type="primary" className="ant-btn-84"
                                                style={marginRight8}>{common.exportStatement}</Button>
                                    </a>
                                    {/*<Button type="primary"  onClick={this.openVINModal}>VIN码下发</Button>*/}
                                </FormItem>
                            </Col>
                        </Row>
                    </form>
                    <Grid rowSelection={rowSelection} 
                          refresh={this.state.refresh} params={this.state.params} columns={this.columns}
                          url="api/user/car/qry"/>
                    <BindVIN selectedRowKeys={this.state.selectedRowKeys} handleCancel={this.handleCancel}
                             visible={this.state.visible4VIN}/>
                    <RemoveVIN selectedRowKeys={this.state.selectedCarVIN} handleCancel={this.handleCancel}
                               visible={this.state.visible4removeVIN}/>
                </div>
            </AuthButton>
        )
    }
}

carManage = createForm()(carManage);
export default injectIntl(carManage);